/* 折扣游戏 - 贪吃蛇 */
class DiscountGame {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.discount = 0;
        this.snake = [];
        this.direction = { x: 1, y: 0 };
        this.food = { x: 0, y: 0 };
        this.gridSize = 20;
        this.canvasSize = 400;
        this.gameSpeed = 150;
        this.gameLoop = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.setupCanvas();
    }

    bindEvents() {
        // 游戏控制按钮（只在元素存在时绑定）
        const startGameBtn = document.getElementById('startGame');
        if (startGameBtn) {
            startGameBtn.addEventListener('click', this.startGame.bind(this));
        }
        
        const pauseGameBtn = document.getElementById('pauseGame');
        if (pauseGameBtn) {
            pauseGameBtn.addEventListener('click', this.togglePause.bind(this));
        }
        
        const resetGameBtn = document.getElementById('resetGame');
        if (resetGameBtn) {
            resetGameBtn.addEventListener('click', this.resetGame.bind(this));
        }
        
        const applyDiscountBtn = document.getElementById('applyDiscount');
        if (applyDiscountBtn) {
            applyDiscountBtn.addEventListener('click', this.applyDiscount.bind(this));
        }
        
        // 键盘控制（只在有canvas时绑定）
        if (this.canvas) {
            document.addEventListener('keydown', this.handleKeyPress.bind(this));
        }
        
        // 模态框关闭时重置游戏（只在元素存在时绑定）
        const closeGameModalBtn = document.getElementById('closeGameModal');
        if (closeGameModalBtn) {
            closeGameModalBtn.addEventListener('click', this.resetGame.bind(this));
        }
    }

    setupCanvas() {
        this.canvas = document.getElementById('gameCanvas');
        if (this.canvas) {
            this.ctx = this.canvas.getContext('2d');
            this.canvas.width = this.canvasSize;
            this.canvas.height = this.canvasSize;
        }
    }

    startGame() {
        if (this.gameRunning) return;
        
        this.gameRunning = true;
        this.gamePaused = false;
        this.score = 0;
        this.discount = 0;
        
        // 初始化蛇
        this.snake = [
            { x: 10, y: 10 },
            { x: 9, y: 10 },
            { x: 8, y: 10 }
        ];
        
        // 初始化方向
        this.direction = { x: 1, y: 0 };
        
        // 生成食物
        this.generateFood();
        
        // 更新UI
        this.updateUI();
        
        // 开始游戏循环
        this.gameLoop = setInterval(this.gameStep.bind(this), this.gameSpeed);
        
        // 更新按钮状态
        document.getElementById('startGame').disabled = true;
        document.getElementById('pauseGame').disabled = false;
        document.getElementById('resetGame').disabled = false;
    }

    togglePause() {
        if (!this.gameRunning) return;
        
        this.gamePaused = !this.gamePaused;
        
        if (this.gamePaused) {
            clearInterval(this.gameLoop);
            document.getElementById('pauseGame').textContent = '继续';
        } else {
            this.gameLoop = setInterval(this.gameStep.bind(this), this.gameSpeed);
            document.getElementById('pauseGame').textContent = '暂停';
        }
    }

    resetGame() {
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.discount = 0;
        
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
            this.gameLoop = null;
        }
        
        // 重置UI
        this.updateUI();
        this.clearCanvas();
        
        // 重置按钮状态
        document.getElementById('startGame').disabled = false;
        document.getElementById('pauseGame').disabled = true;
        document.getElementById('pauseGame').textContent = '暂停';
        document.getElementById('resetGame').disabled = true;
        
        // 隐藏游戏结果
        document.getElementById('gameResult').style.display = 'none';
    }

    gameStep() {
        if (!this.gameRunning || this.gamePaused) return;
        
        // 移动蛇头
        const head = { ...this.snake[0] };
        head.x += this.direction.x;
        head.y += this.direction.y;
        
        // 检查碰撞
        if (this.checkCollision(head)) {
            this.gameOver();
            return;
        }
        
        // 添加新头部
        this.snake.unshift(head);
        
        // 检查是否吃到食物
        if (head.x === this.food.x && head.y === this.food.y) {
            this.score += 10;
            this.discount = Math.min(this.score * 0.5, 30); // 最多30%折扣
            this.generateFood();
            this.updateUI();
        } else {
            // 移除尾部
            this.snake.pop();
        }
        
        // 绘制游戏
        this.draw();
    }

    checkCollision(head) {
        // 检查墙壁碰撞
        if (head.x < 0 || head.x >= this.canvasSize / this.gridSize ||
            head.y < 0 || head.y >= this.canvasSize / this.gridSize) {
            return true;
        }
        
        // 检查自身碰撞
        for (let segment of this.snake) {
            if (head.x === segment.x && head.y === segment.y) {
                return true;
            }
        }
        
        return false;
    }

    generateFood() {
        const maxX = this.canvasSize / this.gridSize;
        const maxY = this.canvasSize / this.gridSize;
        
        do {
            this.food.x = Math.floor(Math.random() * maxX);
            this.food.y = Math.floor(Math.random() * maxY);
        } while (this.snake.some(segment => 
            segment.x === this.food.x && segment.y === this.food.y
        ));
    }

    draw() {
        this.clearCanvas();
        
        // 绘制蛇
        this.ctx.fillStyle = '#4CAF50';
        for (let segment of this.snake) {
            this.ctx.fillRect(
                segment.x * this.gridSize,
                segment.y * this.gridSize,
                this.gridSize - 2,
                this.gridSize - 2
            );
        }
        
        // 绘制蛇头
        this.ctx.fillStyle = '#2E7D32';
        this.ctx.fillRect(
            this.snake[0].x * this.gridSize,
            this.snake[0].y * this.gridSize,
            this.gridSize - 2,
            this.gridSize - 2
        );
        
        // 绘制食物
        this.ctx.fillStyle = '#FF5722';
        this.ctx.fillRect(
            this.food.x * this.gridSize,
            this.food.y * this.gridSize,
            this.gridSize - 2,
            this.gridSize - 2
        );
    }

    clearCanvas() {
        this.ctx.clearRect(0, 0, this.canvasSize, this.canvasSize);
    }

    handleKeyPress(e) {
        if (!this.gameRunning || this.gamePaused) return;
        
        const key = e.key;
        
        switch (key) {
            case 'ArrowUp':
                if (this.direction.y === 0) {
                    this.direction = { x: 0, y: -1 };
                }
                break;
            case 'ArrowDown':
                if (this.direction.y === 0) {
                    this.direction = { x: 0, y: 1 };
                }
                break;
            case 'ArrowLeft':
                if (this.direction.x === 0) {
                    this.direction = { x: -1, y: 0 };
                }
                break;
            case 'ArrowRight':
                if (this.direction.x === 0) {
                    this.direction = { x: 1, y: 0 };
                }
                break;
        }
    }

    gameOver() {
        this.gameRunning = false;
        this.gamePaused = false;
        
        if (this.gameLoop) {
            clearInterval(this.gameLoop);
            this.gameLoop = null;
        }
        
        // 显示游戏结果
        document.getElementById('finalScore').textContent = this.score;
        document.getElementById('finalDiscount').textContent = `${this.discount.toFixed(1)}%`;
        document.getElementById('gameResult').style.display = 'block';
        
        // 更新按钮状态
        document.getElementById('startGame').disabled = false;
        document.getElementById('pauseGame').disabled = true;
        document.getElementById('resetGame').disabled = false;
    }

    updateUI() {
        document.getElementById('gameScore').textContent = this.score;
        document.getElementById('discountPercent').textContent = `${this.discount.toFixed(1)}%`;
    }

    applyDiscount() {
        if (this.discount > 0) {
            // 应用折扣到当前订单
            if (window.orderManager) {
                window.orderManager.applyDiscount(this.discount);
            }
            
            // 关闭游戏模态框
            document.getElementById('discountGameModal').style.display = 'none';
            
            // 显示成功提示
            if (window.authManager) {
                window.authManager.showNotification(`成功获得 ${this.discount.toFixed(1)}% 折扣！`, 'success');
            }
        }
        
        this.resetGame();
    }

    // 显示游戏模态框
    showGameModal() {
        document.getElementById('discountGameModal').style.display = 'block';
        document.body.style.overflow = 'hidden';
        this.resetGame();
    }

    // 隐藏游戏模态框
    hideGameModal() {
        document.getElementById('discountGameModal').style.display = 'none';
        document.body.style.overflow = 'auto';
        this.resetGame();
    }
}

// 创建全局游戏实例
window.discountGame = new DiscountGame();
